/**
 * Copyright (c) 2009-2011, chunquedong(YangJiandong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * History:
 *     2010-05-05  Jed Young  Creation
 */
package chunmap.model.geom;

import java.util.ArrayList;
import java.util.List;

import chunmap.model.coord.CompactedCoordinateArray;
import chunmap.model.coord.Coordinate2D;
import chunmap.model.coord.CoordinateSeq;
import chunmap.model.coord.Position;
import chunmap.model.coord.PrecisionModel;

public class GeometryFactory {
	public PrecisionModel precision;
    private WktReader _wkt;

    public GeometryFactory(PrecisionModel precision)
    {
        this.precision = precision;
        this._wkt = new WktReader();
    }

    public GeometryFactory() { this(PrecisionModel.getDoubleFloatModel()); }

    //------------------------------------------------------------------------

    public <TGeomtetry extends Geometry> GeometryCollection createGeometryCollection(TGeomtetry[] geometrys) 
    {
        List<Geometry> gs=new ArrayList<Geometry>();
        for (TGeomtetry g : geometrys)
        {
            gs.add(g.transform(precision.getTransform()));
        }
        return new MultiGeometry<Geometry>(gs);
    }

    public Polygon createPolygon(CoordinateSeq shell, CoordinateSeq[] holes)
    {
        CoordinateSeq nshell = shell.transform(precision.getTransform());

        if (holes != null && holes.length > 0)
        {
            List<Ring> nholes = new ArrayList<Ring>();
            int i = 0;
            for (CoordinateSeq hole : holes)
            {
                nholes.add( new Ring(hole.transform(precision.getTransform())));
                i++;
            }
            return new Polygon(new Ring(nshell), nholes);
        }
        return new Polygon(new Ring(nshell));
    }
    
    public MultiLineString createMultiLineString(List<CoordinateSeq> seqList){
    	List<LineString> lss = new ArrayList<LineString>();
    	for(CoordinateSeq cq:seqList){
    		CoordinateSeq nca = cq.transform(precision.getTransform());
    		lss.add(new LineString(nca));
    	}
    	return new MultiLineString(lss);
    }

    public LineString createLineString(double[] x, double[] y)
    {
        CoordinateSeq ca = new CompactedCoordinateArray(x, y);
        CoordinateSeq nca = ca.transform(precision.getTransform());
        return new LineString(nca);
    }

    public Position createPoint(double x, double y)
    {
        return new Coordinate2D(precision.format(x), precision.format(y));
    }

    public Geometry readGeometry(String text)
    {
        return _wkt.read(text);
    }
}